//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 闫博123 on 16/1/13.
//  Copyright © 2016年 闫博123. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    // 属性webView
    let webView = UIWebView()
    
    // MARK: 关闭页面
    @objc private func closed()
    {
        // 让授权页面dismiss回去
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 自动填充账号
    @objc private func defaultAccout()
    {
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com' , document.getElementById('passwd').value = 'oyonomg'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func loadView() {
        
        // 将根视图替换为 webView
        view = webView
        
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // tintColor 文字的渲染颜色
        // 只针对当前的导航控制器有效
        //        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        // appearance() 设置全局颜色 一经设置 全局有效 (可以写到AppDelegate里面)
        //        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        
        // 设置导航条
        setNavBar()
        
        // 加载授权页面
        loadOAuthPage()
        
        webView.delegate = self
    }
    
    private func setNavBar()
    {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closed")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccout")
    }
    
    // MARK: 加载授权页面
    private func loadOAuthPage()
    {
        // 获取url
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)!
        
        // 获取request
        let request = NSURLRequest(URL: url)
        
        webView.loadRequest(request)
    }
}

// swift 中 这样可以将同一类的协议方法写在一起 更加好阅读和维护
extension OAuthViewController : UIWebViewDelegate
{
    
    func webViewDidStartLoad(webView: UIWebView)
    {
        // 显示用户等待指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView)
    {
        // 隐藏用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    // 非常重要的协议方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        //        print(request.URL?.absoluteString)
        
        guard let urlString = request.URL?.absoluteString else
        {
            // 无法获取url字符串 就不加载网页
            return false
        }
        
        if urlString.containsString("code=")
        {
            guard let query = request.URL?.query else
            {
                return false
            }
            
            let codeStr = "code="
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(code,query)
            
            // 调用获取授权Token方法
            loadAccessToken(code)
            
            // 不需要页面跳转到回调页面 所以直接return false
            return false
        }
        
        return true
    }
    
    private func loadAccessToken(code : String)
    {
        // 请求token和用户信息
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            
            if !isSuccess
            {
                print("登录失败")
                
                SVProgressHUD.showErrorWithStatus(errorTip)
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("登陆成功")
            
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
}







